package com.aispeech.astools;

import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import com.aispeech.astools.service.SerialTestService;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @author rain  07.11 2019
 */

public class ASTApplication extends Application {

    private final static String TAG = "ASTApplication";
    public final static String SERIAL_SERVICL_BINDER = "serial_servicl_binder";

    private static Context mContext;
    private static Map<String, Binder> mBinderMap;


    private ServiceConnection serialConnection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "onServiceDisconnected: ");
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "onServiceConnected: ");
            mBinderMap.put(SERIAL_SERVICL_BINDER, (Binder) service);
        }
    };

    public static Context getContext() {
        if (mContext == null) {
            throw new RuntimeException("Unknown Error");
        }
        return mContext;
    }

    public static Application getApplication() {
        if (mContext == null) {
            throw new RuntimeException("Unknown Error");
        }
        return (Application) mContext;
    }

    public static Binder getServiceBinder(String bname) {
        Log.d(TAG, "getServiceBinder with: bname = " + bname + "");
        return mBinderMap.get(bname);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        mBinderMap = new HashMap<>();

        Intent bindIntent = new Intent(this, SerialTestService.class);
        bindService(bindIntent, serialConnection, BIND_AUTO_CREATE);

    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        Log.d(TAG, "onTerminate");

        if (null != mBinderMap) {
            mBinderMap.clear();
        }

        unbindService(serialConnection);
    }
}
